//
//  eBook Bundler.m
//  Capstone Project
//
//  Created by Brian Gilreath on 10/27/10.
//  Copyright 2010 GilreathCapstone. All rights reserved.
//

#import <zlib.h>
#import "eBook Bundler.h"
#import "OHbook.h"
#import "ZipArchive.h"
#import "EPUB_Contents_XML_Parser.h"
// its not declared in the header for memory and runtime effiecency

@implementation eBook_Bundler

@synthesize OHBookList, OHBookmarkList, OHHighlightList, OHNoteList;

-(eBook_Bundler*)init{
	if(self = [super init]){
		NSBundle *bundle = [NSBundle mainBundle];
		NSString *pListPath1 = [bundle pathForResource:@"savedBookInformation" ofType:@"plist"];
		NSDictionary *bookDataDictionary = [[NSDictionary alloc] initWithContentsOfFile:pListPath1];
		NSString *pListPath2 = [bundle pathForResource:@"BookInformation" ofType:@"plist"];
		NSMutableDictionary *bookInformationHandler = [[NSDictionary alloc] initWithContentsOfFile:pListPath2];
		
		int numberOfBooks = [[bookDataDictionary objectForKey:@"NumberOfBooks"] intValue];
		// first we grab each book
		BOOL hasDirectoryScannerRun = [[bookDataDictionary objectForKey:@"HasDirectoryScannerRan"] boolValue];
		if (hasDirectoryScannerRun == NO) {
			//NSLog(@"We need to rebuild a book directory");
			NSArray *epubBooks = [bundle pathsForResourcesOfType:@"epub" inDirectory:nil];
			OHbook *book = [OHbook alloc];
			ZipArchive* za = [[ZipArchive alloc] init];
			for (NSString *eBookPath in epubBooks){
				// extract the ebook
				printf(eBookPath);
				printf("\n");
				if( [za UnzipOpenFile:eBookPath] ){
					NSString *newString = [eBookPath stringByAppendingString:@"d"];
					BOOL ret = [za UnzipFileTo:newString overWrite:YES];
					if( NO==ret )
					{
						// error handler here TODO
						NSLog(@"Unable to read from file at %@", eBookPath);
						continue;
					}
					
					// read the necessary information
					NSArray *origContents = [[NSFileManager defaultManager] directoryContentsAtPath:newString];
					NSLog(@"Number of files = %d", origContents.count);
					
					BOOL isEPUB = NO;
					for (int i = 0; i < origContents.count; i++) {
						NSLog (@"%d: <%@>", i, [origContents objectAtIndex:i]);	
						if ([[origContents objectAtIndex:i] isEqualToString:@"META-INF"]) {
							isEPUB = YES;
						}
					}
					if (isEPUB == YES) {
						// read the necessary data from the container.xml file
						NSURL *url = [NSURL fileURLWithPath:[newString stringByAppendingString:@"/META-INF/container.xml"]];
						NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
						EPUB_Contents_XML_Parser *parser = [[EPUB_Contents_XML_Parser alloc] init];
						[xmlParser setDelegate:parser];
						[xmlParser shouldResolveExternalEntities];
						if(![xmlParser parse]){
							NSLog(@"Something is wrong with %@",url);
						}
						NSURL *OEBPSURL = [NSURL fileURLWithPath:[newString stringByAppendingString:[@"/" stringByAppendingString:[parser getPathOfOEBPS]]]];
						[xmlParser release];
						[parser release];
						// now reading contents of our other file
						NSString *loveit = [OEBPSURL path];
						NSLog(@"%@",loveit);
						//[xmlParser setDelegate:self];
						//[xmlParser shouldResolveExternalEntities:YES];
			            // following ebook standard (OEBS), it should be as follows:
						// NSArray *data = [xmlParser mutableArrayValueForKey:@"rootfile"];
						//						NSArray *data = [xmlParser mutableArrayValueForKey:@"rootfiles"];
						// NSLog(@"%d", data.count);
						//						NSString *temp = [NSString stringWithContentsOfFile:[newString stringByAppendingString:@"/META-INF/container.xml"]];
						//						NSLog(temp);
						//						NSArray *bloom = [[NSFileManager defaultManager] directoryContentsAtPath:[newString stringByAppendingString:@"/META-INF"]];
						//						
						//						for (int i = 0; i < bloom.count; i++) {
						//							NSLog (@"%d: <%@>", i, [bloom objectAtIndex:i]);	
						//						}
					}
					
					
					// close the file
					[za UnzipCloseFile];
				}
			}
			[za release];
			// set directory scan variable to true
			//[bookDataDictionary setValue:[NSNumber numberWithBool:YES] forKey:@"HasDirectoryScannerRan"];
			// save TODO
		}
		
		//		NSString *bunleRoot = [[NSBundle mainBundle] bundlePath];
		//		NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
		//		NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]]
		//		[bundleRoot release];
		//		for (NSString *string in dirContents){
		//			NSLog(string);
		//		}
	}
	return self;
}

OHbook *EBCurrentBookOpened;

// The only thing this method does is loading the webview manager with the appropriate book
// html file, advanced implementations involve adding various functions, such as overlays
// and note taker areas, highlighting, etc.
-(int)OHopenBook:(OHbook *)book{
	EBCurrentBookOpened = book;
	// todo unload book
	// todo figure out associated objects
	// todo load first page into view, giving it an index to reference from
	return 0;
}


// In order to safely open another book, you must call the close book method to deallocate 
// the memory used for the open book
-(int)OHcloseBook{
	return 0;
}

-(int)OHcreateNote:(OHnote *)newNote{
	if (![OHNoteList containsObject:newNote]) {
		[OHNoteList addObject:newNote];
		return itemCreatedSuccessfully;
	}
	return itemNotCreated;
}

-(int)OHcreateHighlight:(OHhighlight *)newHighlight{
	if (![OHHighlightList containsObject:newHighlight]) {
		[OHHighlightList addObject:newHighlight];
		return itemCreatedSuccessfully;
	}
	return itemNotCreated;
}

-(int)OHcreateBookmark:(OHbookmark *)newBookmark{
	if (![OHBookmarkList containsObject:newBookmark]) {
		[OHBookmarkList addObject:newBookmark];
		return itemCreatedSuccessfully;
	}
	return itemNotCreated;
}

-(int)OHeditNote:(OHnote *)newNote:(OHnote *)oldNote{
	if (newNote == nil) {
		return itemNotEdited;
	}
	int index = [OHNoteList indexOfObject:oldNote];
	if ( index != NSNotFound) {
		[OHNoteList replaceObjectAtIndex:index
							  withObject:newNote];
		return itemEditedSuccessfully;
	}
	return itemDNE;
}

-(int)OHeditHighlight:(OHhighlight *)newHighlight:(OHhighlight *)oldHighlight{
	if (newHighlight == nil) {
		return itemNotEdited;
	}
	int index = [OHHighlightList indexOfObject:oldHighlight];
	if ( index != NSNotFound) {
		[OHHighlightList replaceObjectAtIndex:index
								   withObject:newHighlight];
		return itemEditedSuccessfully;
	}
	return itemDNE;
}

-(int)OHeditBookmark:(OHbookmark *)newBookmark:(OHbookmark *)oldBookmark{
	if (newBookmark == nil) {
		return itemNotEdited;
	}
	int index = [OHBookmarkList indexOfObject:oldBookmark];
	if ( index != NSNotFound) {
		[OHBookmarkList replaceObjectAtIndex:index
								  withObject:newBookmark];
		return itemEditedSuccessfully;
	}
	return itemDNE;
}

-(int)OHdeleteNote:(OHnote *)noteToDelete{
	int index = [OHNoteList indexOfObject:noteToDelete];
	if ( index != NSNotFound) {
		[OHNoteList removeObjectAtIndex:index];
		return itemRemoved;
	}
	return itemDNE;
}

-(int)OHdeleteHighlight:(OHhighlight *)highlightToDelete{
	int index = [OHHighlightList indexOfObject:highlightToDelete];
	if ( index != NSNotFound) {
		[OHNoteList removeObjectAtIndex:index];
		return itemRemoved;
	}
	return itemDNE;
}

-(int)OHdeleteBookmark:(OHbookmark *)bookmarkToDelete{
	int index = [OHBookmarkList indexOfObject:bookmarkToDelete];
	if ( index != NSNotFound) {
		[OHNoteList removeObjectAtIndex:index];
		return itemRemoved;
	}
	return itemDNE;
}

@end
